package org.example.erat.parser;

import org.example.erat.exception.FileParseException;
import org.example.erat.exception.InvalidFileNameException;
import org.example.erat.log.core.LoggerSingleton;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * CSV文件解析器
 * 用于解析.csv文件
 */
public class CsvFileParser implements FileParser {

    private static final Pattern FILE_NAME_PATTERN = Pattern.compile("(.+)_([0-9]+)_(.+)\\.csv");

    @Override
    public Map<String, Object> parse(File file) throws IOException {
        LoggerSingleton.getInstance().info("开始解析CSV文档: " + file.getName());

        // 解析文件名
        Map<String, String> fileNameInfo = extractInfoFromFileName(file.getName());
        if (fileNameInfo.isEmpty()) {
            throw new FileParseException("文件名格式不正确: " + file.getName());
        }

        // 解析CSV文件内容
        List<Map<String, Object>> rows = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            String[] headers = null;

            // 读取表头
            if ((line = reader.readLine()) != null) {
                headers = line.split(",");
                for (int i = 0; i < headers.length; i++) {
                    headers[i] = headers[i].trim();
                }
            }

            // 读取数据行
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                String[] values = line.split(",");
                Map<String, Object> rowData = new HashMap<>();

                for (int i = 0; i < headers.length && i < values.length; i++) {
                    rowData.put(headers[i], values[i].trim());
                }

                rows.add(rowData);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("fileName", file.getName());
        result.put("filePath", file.getAbsolutePath());
        result.put("fileSize", file.length());
        result.put("rows", rows);
        result.put("experimentName", fileNameInfo.get("experimentName"));
        result.put("studentId", fileNameInfo.get("studentId"));
        result.put("studentName", fileNameInfo.get("studentName"));

        LoggerSingleton.getInstance().info("CSV文档解析完成: " + file.getName() + ", 共 " + rows.size() + " 行数据");
        return result;
    }

    @Override
    public String getSupportedFileType() {
        return "csv";
    }

    @Override
    public boolean validateFileName(String fileName) {
        return FILE_NAME_PATTERN.matcher(fileName).matches();
    }

    @Override
    public Map<String, String> extractInfoFromFileName(String fileName) {
        Map<String, String> result = new HashMap<>();

        Matcher matcher = FILE_NAME_PATTERN.matcher(fileName);
        if (matcher.matches()) {
            String experimentName = matcher.group(1);
            String studentId = matcher.group(2);
            String studentName = matcher.group(3);

            result.put("experimentName", experimentName);
            result.put("studentId", studentId);
            result.put("studentName", studentName);
        } else {
            LoggerSingleton.getInstance().warn("文件名格式不正确: " + fileName + "，应为: 实验名_学号_姓名.csv");
            throw new InvalidFileNameException("文件名格式不正确: " + fileName + "，应为: 实验名_学号_姓名.csv");
        }

        return result;
    }
}
